/* Filename: mmap.c
 * Description: 给定文件，数出有多少个'a'
 * Last modified: humble 20200502 15:39
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

static void usage(void);

int main(int argc, char **argv)
{
    int fd;
    struct stat statres;
    char *str;
    int i;
    int64_t count = 0;

    if(argc != 2){
        fprintf(stderr, "argc != 2");
        usage();
        exit(1);
    }

    fd = open(argv[1], O_RDONLY);
    if(fd < 0){
        perror("open()");
        exit(1);
    }

    if(fstat(fd, &statres) < 0){
        perror("fstat()");
        exit(1);
    }

    str = mmap(NULL, statres.st_size, PROT_READ, MAP_SHARED, fd, 0);
    if(str == MAP_FAILED){
        perror("mmap()");
        exit(1);
    }

    close(fd);

    for(i = 0; i < statres.st_size; i++)
    {
        if(str[i] == 'a'){
            count++;
        }
    }

    printf("%ld\n", count);

    if(munmap(str, statres.st_size) < 0){
        perror("mmap()");
        exit(1);
    }

    return 0;
}

static void usage(void)
{
#define USAGE "Usage:\n\
  Helloworld\n"
    printf(USAGE);
}
